<?php


namespace App\Http\Controllers\Admin;
use App\Http\Controllers\BaseController;
use App\Jobs\DeleteAttach;
use App\Jobs\DeleteStar;
use App\Models\Cookbook;
use App\Models\Notebook;
use App\Models\Star;
use App\Models\User;
use Illuminate\Http\Request;

class NotebookController extends BaseController
{

    public $model = Notebook::class;


    public function index(Request $request) {
        $model = new Notebook();
        $nickname = $request->input('nickname');
        $start_at = $request->input('start_at');
        $end_at = $request->input('end_at');
        $order_by_key = $request->input('order_by_key', 'sort');
        $order_by_value = $request->input('order_by_value', 'desc');


        $list = $model->when($nickname, function ($q) use($nickname){
            $q->whereHas('user', function ($qr) use($nickname) {
                $qr->where('nickname', 'like', '%'.$nickname.'%');
            });
        })  ->startAt($start_at)
            ->endAt($end_at)->withCertain('cookbook', ['title'])
            ->withCertain('user', ['nickname', 'avatar_url'])
            ->orderBy($order_by_key, $order_by_value)
            ->orderBy('id', 'desc')
            ->paginate(\request('per_page', 20));
        return $this->paginate($list);
    }

    public function destroy(Request $request) {
        $this->validate($request, [
            'ids' => 'required'
        ]);
        $ids = $request->input('ids');
        $arr_id = explode(",", $ids);

        foreach ($arr_id as $id) {
            $model = $this->model::find($id);
            $user_id = $model->user_id;
            $user = User::find($user_id);
            $attach = $model->file_path;
            if ($user->notebook_count)
                $user->increment('notebook_count', -1);

            if ($model->cookbook_id)
                Cookbook::where('id', $model->cookbook_id)->increment('note_num', -1);

            if ($model->delete()) {
                dispatch(new DeleteAttach($attach));
                dispatch(new DeleteStar(Star::TYPE_NOTEBOOK, $id, $user_id));
            }
        }

        return $this->success([]);
    }


}

